import requests
from bs4 import BeautifulSoup

def fetch_lottery_data():
    url = 'https://www.cwl.gov.cn/ygkj/wqkjgg/'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
        'Referer': 'https://www.cwl.gov.cn/',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
    }
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        response.encoding = response.apparent_encoding
        soup = BeautifulSoup(response.text, 'html.parser')

        # 这里需要根据实际网页结构调整选择器
        # 假设期号在 <span class="issue-number"> 标签中
        issue_number_tag = soup.find('span', class_='issue-number')
        issue_number = issue_number_tag.get_text(strip=True) if issue_number_tag else '未找到期号'

        # 假设开奖日期在 <span class="draw-date"> 标签中
        draw_date_tag = soup.find('span', class_='draw-date')
        draw_date = draw_date_tag.get_text(strip=True) if draw_date_tag else '未找到开奖日期'

        # 假设开奖号码在 <div class="draw-numbers"> 标签中
        draw_numbers_tag = soup.find('div', class_='draw-numbers')
        draw_numbers = draw_numbers_tag.get_text(strip=True) if draw_numbers_tag else '未找到开奖号码'

        # 准备要写入文件的数据
        data_to_write = f"期号: {issue_number}\n开奖日期: {draw_date}\n开奖号码: {draw_numbers}"

        # 打开文件并写入数据，'w' 模式会清空原有数据
        file_path = r'C:\workspace\fortune-lottery-prediction\lottery_data.txt'
        with open(file_path, 'w', encoding='utf-8') as file:
            file.write(data_to_write)
        print(f'彩票数据已保存到 {file_path}')

    except requests.RequestException as e:
        print(f'请求出错: {e}')

if __name__ == '__main__':
    fetch_lottery_data()